﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using BLL = KC.Business.BlogSlinger;
using DAL = KC.DataAccess.BlogSlinger;

public partial class admin: System.Web.UI.Page
{
	private int BlogID;

	protected void Page_Load(object sender, EventArgs e)
	{
		DAL.User user = Master.user;
		if (user == null) {
			pnlBlogs.Visible = false;
			Master.UpdateErr("You must be logged in to manage your Blogs");
			return; }

		string _blogID = Request.QueryString["BlogID"];
		if (int.TryParse(_blogID, out BlogID))
			LoadBlog(BlogID);
		else
			LoadBlogs();

		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", BlogID > 0 ? "Blog ID " + BlogID.ToString() : "Browsed admin section (No Blog ID)", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void rBlogs_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		// select new { BlogID = b.BlogID, Name = b.Blog.Name, RelationshipType = b.RelationshipType };
		if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
			return;
		HyperLink hlBlog = (HyperLink)e.Item.FindControl("hlBlog");
		DAL.UserRole role = (dynamic)e.Item.DataItem;
		hlBlog.Text = role.Blog.Name;
		hlBlog.NavigateUrl = "admin.aspx?BlogID=" + role.BlogID.ToString();

		Label lblRelationshipType = (Label)e.Item.FindControl("lblRelationshipType");
		lblRelationshipType.Text = "Blog #" + role.BlogID.ToString() + "; " + role.RelationshipType;
	}

	// Big Picture PanelS
	protected void btnAddBlog_Click(object sender, EventArgs e)
	{
		pnlBlogs.Visible = false;
		pnlNewBlog.Visible = true;
		txtCreateBlogName.Text = "";
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked Add New Blog", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnNewBlogCxl_Click(object sender, EventArgs e)
	{
		pnlNewBlog.Visible = false;
		pnlBlogs.Visible = true;
		txtCreateBlogName.Text = "";
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Cancelled adding a new Blog", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnNewBlogOK_Click(object sender, EventArgs e)
	{
		pnlNewBlog.Visible = false;
		pnlBlogs.Visible = true;
		int BlogID = BLL.CreateBlog(ref Master.dc, Master.user.ID, txtCreateBlogName.Text);
		LoadBlogs();
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Created Blog ID " + BlogID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}

	// Admin Panels
	protected void btnManagePosts_Click(object sender, EventArgs e)
	{
		HideAdminPanels();
		pnlManagePosts.Visible = true;
		LoadPosts();
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked 'Manage Posts'", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnAddPost_Click(object sender, EventArgs e)
	{
		HideAdminPanels();
		pnlEditPost.Visible = true;
		ResetPostEditor();
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked 'Add Post'", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnManageCategories_Click(object sender, EventArgs e)
	{
		HideAdminPanels();
		pnlManageCategories.Visible = true;
		LoadCats();
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked 'Manage Categories'", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnManageLinks_Click(object sender, EventArgs e)
	{
		HideAdminPanels();
		pnlManageLinks.Visible = true;
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked 'Manage Links'", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	private void HideAdminPanels()
	{
		pnlManagePosts.Visible = false;
		pnlEditPost.Visible = false;
		pnlManageLinks.Visible = false;
		pnlManageCategories.Visible = false;
	}

	// Post Management
	private void LoadBlogs()
	{
		rBlogs.DataSource = BLL.GetBlogsByUser(ref Master.dc, Master.user.ID);
		rBlogs.DataBind();
	}
	private void LoadBlog(int id)
	{
		pnlBlogs.Visible = false;
		var blogs = from p in BLL.GetBlogsByUser(ref Master.dc, Master.user.ID) where p.UserID == Master.user.ID && p.BlogID == id select p;
		if (blogs.Count() == 0)
		{
			Master.UpdateErr("Error: User " + Master.user.ID.ToString() + " is not entitled to manage Blog " + id.ToString());
			return;
		}
		DAL.Blog blog = blogs.First().Blog;

		pnlBlogAdmin.Visible = true;
		BlogID = id;
		hlManageBlog.Text = blog.Name;
		hlManageBlog.NavigateUrl = "Blog.aspx?ID=" + BlogID.ToString();

		hlRSS.NavigateUrl = "rss.aspx?ID=" + BlogID.ToString();
	}
	private void ResetPostEditor()
	{
		// reset and clear all fields in the post editor
		lbPostCategories.DataSource = BLL.GetCategories(ref Master.dc, BlogID);
		lbPostCategories.DataBind();
		txtPostBody.Text = "";
		txtPostTitle.Text = "";
		cbPostComments.Checked = false;
		cbPostEnabled.Checked = false;
		lblPostID.Text = "(none)";

		// Four whole lines just for the month :(
		ddlPostMonth.Items.Clear();
		for (int i = 1; i < 13; i++)
			ddlPostMonth.Items.Add(new ListItem(DateTime.Parse(i.ToString() + "/01/2000 00:00:00").ToString("MMM"), i.ToString()));
		ddlPostMonth.SelectedIndex = DateTime.Now.Month - 1;

		// rest of the publish date
		txtPostDay.Text = DateTime.Today.Day.ToString();
		txtPostYear.Text = DateTime.Today.Year.ToString();
		txtPostHour.Text = DateTime.Now.Hour.ToString();
		txtPostMinute.Text = DateTime.Now.Minute.ToString();
	}
	private void LoadPosts()
	{
		rPosts.DataSource = BLL.GetPostsByBlog(ref Master.dc, BlogID, 65536);
		rPosts.DataBind();
	}

	protected void btnPostCxl_Click(object sender, EventArgs e)
	{
		ResetPostEditor();
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Cancelled out of the Post Editor", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
	protected void btnPostOK_Click(object sender, EventArgs e)
	{
		int PostID = 0;
		int.TryParse(lblPostID.Text, out PostID);
		bool isEdit = PostID > 0;

		// Parse publish date
		DateTime dtPublish;
		try { dtPublish = DateTime.Parse(ddlPostMonth.SelectedValue + "/" + txtPostDay.Text + "/" + txtPostYear.Text + " " + txtPostHour.Text + ":" + txtPostMinute.Text); }
		catch {
			BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Tried to save a Post, but failed due to a bad publish date", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
			dtPublish = DateTime.Now; 
			Master.UpdateErr("Could not parse publish date. Using \"right now\" instead."); }

		// Clear and Add Categories
		List<DAL.Category> cats = new List<DAL.Category>();
		foreach (ListItem li in lbPostCategories.Items)
			if (li.Selected)
				cats.Add((from c in Master.dc.Categories where c.ID == int.Parse(li.Value) select c).First());

		// do save
		try { PostID = (int)BLL.SavePost(
			ref Master.dc, 
			PostID, 
			Master.user.ID, 
			BlogID, 
			cbPostEnabled.Checked, 
			KC.Business.Text.BlogEncodeForStorage(txtPostBody.Text),
			KC.Business.Text.StripHTML(txtPostTitle.Text),
			KC.Business.Text.StripHTML(txtPostExcerpt.Text),
			dtPublish, 
			cbPostComments.Checked, 
			int.Parse(ddlPostType.SelectedValue), 
			cats); }
		catch {
			BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Tried to save a Post, but failed due to an error", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
			Master.UpdateErr("Error saving post, please try again later"); 
			return; }
		Master.UpdateErr("Post saved successfully!");
		Master.dc.SubmitChanges();

		// Update page
		DAL.Post post = BLL.GetPost(ref Master.dc, PostID);
		hlPreview.NavigateUrl = "Post.aspx?Title=" + post.FriendlyName;
		hlPreview.Enabled = true;
		pnlEditPost.Visible = false;
		ResetPostEditor();
		LoadPostEditor(post);
		Master.dc.SubmitChanges();

		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Saved Post " + post.ID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));

		if (cbPostWall.Checked)
		{
			BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked 'Add Post'", Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
			if (Master.token == null) Master.token = (string)Session["token"];
			Dictionary<string, string> dict = new Dictionary<string, string>();

			// TODO: For delayed publishing, post to wall upon publish.
			dict.Add("message", isEdit
				? ("I updated a blog post on my blog \"" + post.Blog.Name + "\", entitled \"" + post.Title + "\". Visit the blog to read the full post! http://blogs.code-slinger.com/Post.aspx?Title=" + post.FriendlyName)
				: ("I published a New blog post on my blog \"" + post.Blog.Name + "\", entitled \"" + post.Title + "\". Visit the blog to read the full post! http://blogs.code-slinger.com/Post.aspx?Title=" + post.FriendlyName
					+ (string.IsNullOrEmpty(post.Excerpt) ? "" : "\r\nHere's an excerpt of the Post:\r\n\r\n" + post.Excerpt))
				);
			try { new FacebookAPI(Master.token).Post("/" + Master.user.FacebookUserID + "/feed", dict); }
			catch (FacebookAPIException) { } // TODO: Log Error
		}


	}
	protected void rPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
			return;
		DAL.Post post = (DAL.Post)e.Item.DataItem;

		((Label)e.Item.FindControl("lblTitle")).Text = HttpUtility.HtmlEncode(post.Title);
		((Label)e.Item.FindControl("lblExcerpt")).Text = HttpUtility.HtmlEncode(post.Excerpt);
		((Label)e.Item.FindControl("lblDate")).Text = post.ModifyDate.ToString("MM/dd/yy HH:mm");

		((Button)e.Item.FindControl("btnEdit")).Attributes.Add("PostID", post.ID.ToString());
		((Button)e.Item.FindControl("btnDelete")).Attributes.Add("PostID", post.ID.ToString());
		Button btnEnable = ((Button)e.Item.FindControl("btnEnable"));
		btnEnable.Attributes.Add("PostID", post.ID.ToString());
		btnEnable.Text = post.Status == "Active" ? "Disable" : "Enable";
	}
	protected void btnEnable_Click(object sender, EventArgs e)
	{
		Button btnEnable = (Button)sender;
		int PostID = int.Parse(btnEnable.Attributes["PostID"]);
		BLL.TogglePostEnabled(ref Master.dc, PostID, btnEnable.Text == "Enable");
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", (btnEnable.Text == "Enable" ? "Enabled" : "Disabled") + " Post " + PostID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		LoadPosts();
	}
	protected void btnEdit_Click(object sender, EventArgs e)
	{
		ResetPostEditor();
		DAL.Post post = BLL.GetPost(ref Master.dc, int.Parse(((Button)sender).Attributes["PostID"]));
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked Edit on Post " + post.ID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		LoadPostEditor(post);
	}
	protected void btnDelete_Click(object sender, EventArgs e)
	{
		DAL.Post post = BLL.GetPost(ref Master.dc, int.Parse(((Button)sender).Attributes["PostID"]));
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Deleted Post " + post.ID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		BLL.DeletePost(ref Master.dc, post.ID);
		LoadPosts();
	}
	private void LoadPostEditor(DAL.Post post)
	{
		pnlManagePosts.Visible = false;
		pnlEditPost.Visible = true;
		txtPostTitle.Text = post.Title;
		lblPostID.Text = post.ID.ToString();
		ddlPostMonth.SelectedIndex = post.PublishDate.Month - 1;
		txtPostDay.Text = post.PublishDate.Day.ToString();
		txtPostYear.Text = post.PublishDate.Year.ToString();
		txtPostHour.Text = post.PublishDate.Hour.ToString();
		txtPostMinute.Text = post.PublishDate.Minute.ToString();
		txtPostBody.Text = KC.Business.Text.BlogDecodeForEditing(post.Body);
		txtPostExcerpt.Text = post.Excerpt;
		cbPostEnabled.Checked = post.Status == "Active";
		cbPostComments.Checked = post.isAllowComments;
		hlPreview.Enabled = true;
		hlPreview.NavigateUrl = "./Post.aspx?Title=" + post.FriendlyName;

		lbPostCategories.ClearSelection();
		foreach (DAL.PostToCategory ptc in post.PostToCategories)
			foreach (ListItem li in lbPostCategories.Items)
				if (li.Value == ptc.CategoryID.ToString())
					li.Selected = true;
	}

	// Category Management
	protected void btnAddCat_Click(object sender, EventArgs e)
	{
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Created Category " + txtAddCat.Text + " on Blog " + BlogID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		BLL.SaveCategory(ref Master.dc, txtAddCat.Text, "", BlogID);
		txtAddCat.Text = "";
		LoadCats();
	}
	private void LoadCats()
	{
		rCatManager.DataSource = BLL.GetCategories(ref Master.dc, BlogID);
		rCatManager.DataBind();
	}
	protected void rCatManager_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
			return;

		DAL.Category cat = (DAL.Category)e.Item.DataItem;
		HyperLink hlCategory = (HyperLink)e.Item.FindControl("hlCategory");
		hlCategory.Text = cat.Name;
		hlCategory.NavigateUrl = "Category.aspx?ID=" + cat.ID.ToString();
		hlCategory.ToolTip = "Browse category " + cat.Name + " for Blog " + cat.Blog.Name;

		((Button)e.Item.FindControl("btnEditCat")).Attributes.Add("CatID", cat.ID.ToString());
		((Button)e.Item.FindControl("btnDelCat")).Attributes.Add("CatID", cat.ID.ToString());
	}
	protected void btnEditCat_Click(object sender, EventArgs e)
	{
		int CatID = int.Parse(((Button)sender).Attributes["CatID"]);
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Clicked Edit on Category " + CatID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		// TODO: Editing Categories
	}
	protected void btnDelCat_Click(object sender, EventArgs e)
	{
		int CatID = int.Parse(((Button)sender).Attributes["CatID"]);
		BLL.DeleteCategory(ref Master.dc, CatID);
		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Admin page", "Deleted Category " + CatID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
	}
}